package com.om.userpath.openeuler;

import Utils.HttpClientUtils;
import com.om.common.CommonProperties;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;

public class CopyIndex extends CommonProperties {
    private static final HashMap<String, String> indexPlatformMap = new HashMap<>();
    private static final HashMap<String, String> indexFieldsMap = new HashMap<>();

    static {
        //index对应的平台名，例如
        indexPlatformMap.put("indexName", "platformName");

        //index对应抽取的字段，例如
        indexFieldsMap.put("indexName", "[\"field1\",\"field2\",\"field3\"]");
    }

    public static void main(String[] args) {
        String[] sourceIndexs = args[0].split(",");
        String targetIndex = args[1];
        String startTime = args[2];
        String endTime = args[3];

        CloseableHttpClient client = null;

        try {
            client = HttpClientUtils.getClient();
            for (String sourceIndex : sourceIndexs) {
                filterCopyIndex(sourceIndex, targetIndex, startTime, endTime, client);
            }
        } finally {
            try {
                assert client != null;
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void filterCopyIndex(String sourceIndex, String targetIndex, String startTime, String endTime, CloseableHttpClient client) {
        try {
            client = HttpClientUtils.getClient();
            URI geturi = new URIBuilder().setScheme(SCHEME).setHost(HOST).setPort(Integer.parseInt(PORT)).setPath("_reindex").build();
            HttpPost httpPost = new HttpPost(geturi);
            httpPost.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
            httpPost.addHeader("Authorization", auth);
            String stringEntity = "{\"source\": {\"index\": \"" + sourceIndex + "\"," +
                    "\"_source\": {\"includes\": " + indexFieldsMap.get(sourceIndex) + "}," +
                    "\"query\": {\"bool\": {\"filter\": {\"range\": {\"created_at\": {\"gte\": \"" + startTime + "\",\"lt\": \"" + endTime + "\"}}}}}}," +
                    "\"dest\": {\"index\": \"" + targetIndex + "\"}}";
            System.out.println(stringEntity);
            httpPost.setEntity(new StringEntity(stringEntity, "UTF-8"));
            CloseableHttpResponse getDataResponse = client.execute(httpPost);
            getDataResponse.close();

            int count = 0;
            while (count < 60) {
                Thread.sleep(1000);
                CloseableHttpResponse platformResponse = addPlatfrom(client, sourceIndex, targetIndex);
                System.out.println(count + "--" + platformResponse);
                count++;
                int code = platformResponse.getStatusLine().getStatusCode();
                if (code == 200 || code == 201) break;

                platformResponse.close();
            }
        } catch (IOException | URISyntaxException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static CloseableHttpResponse addPlatfrom(CloseableHttpClient client, String sourceIndex, String targetIndex) throws URISyntaxException, IOException {
        URI postUri = new URIBuilder().setScheme(SCHEME).setHost(HOST).setPort(Integer.parseInt(PORT)).setPath("/" + targetIndex + "/_update_by_query").build();
        HttpPost httpPost = new HttpPost(postUri);
        httpPost.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
        httpPost.addHeader("Authorization", auth);

        String stringEntity = "{\"script\": {\"lang\": \"painless\"," +
                "\"source\": \"if (ctx._source.platform == null) {ctx._source.platform = '" + indexPlatformMap.get(sourceIndex) + "'}\"}}";
        System.out.println(stringEntity);
        httpPost.setEntity(new StringEntity(stringEntity, "UTF-8"));

        return client.execute(httpPost);
    }
}
